import axios, {AxiosInterceptorManager, AxiosRequestConfig, AxiosResponse} from "axios";
import printLog from "./printLog";
import store from '../store';
import {message} from 'ant-design-vue';
import {ResponseType} from "../types/Response";
import {toRefreshToken} from "../api/UserActionRequest";
import {searchCart} from "../api/CartRequest";


//@ts-ignored
const base_request_url: string = import.meta.env.VITE_APP_BASE_REQUEST_URL != null ? import.meta.env.VITE_APP_BASE_REQUEST_URL.toString() : ''

const http = axios.create({
    baseURL: base_request_url,
    timeout: 10000
})

let requestArray: Function[] = [];
let isRefreshing: boolean = false;

http.interceptors.request.use((request: AxiosRequestConfig) => {
    printLog.info("<--", request.url, request.data==null?request.params:request.data)
    if (store.state.config.token != null && store.state.config.token.length > 0) {
        request.headers.Authorization = 'Bearer ' + store.state.config.token;
    }

    if (store.state.config.languageId != null && store.state.config.languageId.length > 0) {
        request.headers.Language = store.state.config.languageId;
    }

    return request;
})

http.interceptors.response.use(async (response: AxiosResponse<ResponseType>) => {

    printLog.info("-->", response.config.url, response.data);
    let {config} = response;
    let {result, status, message} = response.data;

    if(status == 200){
        return response
    }

    if (status == 500) {
        throw response
    }

    if ([104, 105].indexOf(status)>-1) {
        response.data.message = '请先登录'
        throw response;
    }

    if ([101, 102, 103].indexOf(status)>-1) {
        if ([101, 102, 103].indexOf(status)>-1) {
            if (store.state.config.refreshToken != null && store.state.config.refreshToken.trim().length > 0) {
                return new Promise(async (resolve) => {
                    requestArray.push(() => {
                        resolve(http.request(config))
                    })
                    if (!isRefreshing) {
                        isRefreshing = true
                        //@ts-ignored
                        await toRefreshToken(store.state.config.refreshToken).then(async (res) => {
                            store.commit('SET_CONFIG', {
                                token: res.data.result?.token,
                                refreshToken: res.data.result?.refreshToken
                            })
                            store.commit('SET_GLOBAL_INFO', {
                                userInfo:res.data.result?.user
                            })
                            searchCart().then((res)=>{
                                if(res.data.result!=undefined&&res.data.result.cartList!=null){
                                    for (let i = 0; i < res.data.result.cartList.length; i++) {
                                        //@ts-ignored
                                        res.data.result.cartList[i].good.specification.specification=JSON.parse(res.data.result.cartList[i].good.specification.specification)
                                    }
                                }
                                store.commit('SET_GLOBAL_INFO',{cartInfo: res.data.result})
                            })
                            requestArray.forEach(f => f())
                        }).catch((res) => {
                            store.commit('CLEAR_LOGIN_INFO')
                            requestArray = []
                        }).finally(() => {
                            isRefreshing = false
                        })
                    }
                })
            } else {
                response.data.message = '请先登录'
                throw response
            }
        }
    } else {
        throw response;
    }
    return response
})

export default http;
